package org.easy.tool.common;

import cn.hutool.core.io.IoUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;

/**
 * @author Valley
 * Created by Valley on 2023/9/6 18:52
 */
public class IOUtil {

    /**
     * 功能：将本地文件转化为输出流
     */
    public static InputStream fileToInput(File file) {
        return IoUtil.toStream(file);
    }

    /**
     * 功能：将文件转化为字节
     */
    public static byte[] fileToByte(File file) throws Exception{
        ByteArrayOutputStream out = (ByteArrayOutputStream)fileToOut(file);
        byte[] bytes = out.toByteArray();
        out.close();
        return bytes;
    }

    /**
     * 功能：将文件转化为输出流
     */
    public static OutputStream fileToOut(File file) throws Exception{
        InputStream in = fileToInput(file);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int len;
        byte[] buffer = new byte[1024];
        while ((len = in.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
        in.close();
        return out;
    }

    /**
     * 功能：将输入流转化为文件
     */
    public static void inputToFile(InputStream in, String path) throws Exception{
        OutputStream out = Files.newOutputStream(new File(path).toPath());
        IoUtil.copy(in, out);
        out.flush();
        out.close();
    }

    /**
     * 功能：将请求中的文件流转化为本地文件
     */
    public static void uploadFile(HttpServletRequest req, String file) throws Exception{
        //这一步可有可没有，直接用req.getInputStream()也一样
        InputStream in = handleFileUpload(req);
        inputToFile(in, file);
        in.close();
    }

    /**
     * 功能：从Http请求中获取文件输入流
     */
    public static InputStream handleFileUpload(HttpServletRequest req) {
        // 获取上传文件的总大小
        long size = req.getContentLength();
        // 创建一个数组来存储读取的数据
        byte[] buffer = new byte[(int)size];
        // 获取输入流
        BufferedInputStream inputStream = null;
        try {
            inputStream = new BufferedInputStream(req.getInputStream());
            int bytesRead = inputStream.read(buffer);
            // 在这里处理文件内容，bytesRead是读取的字节数，buffer数组是包含文件内容的字节数组
            System.out.println(bytesRead+"bytes");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return inputStream;
    }

    /**
     * 功能：将指定本地文件下载到浏览器
     */
    public static void download(HttpServletRequest req, HttpServletResponse res, String path) throws Exception{
        HttpUtil.downloadFile(req, res, new File(path));
    }




}
